/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.sentry;

import io.sentry.util.Objects;

import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * SendFireAndForgetOutboxSender
 *
 * @since 2021-06-02
 **/
@ApiStatus.Internal
public final class SendFireAndForgetOutboxSender
    implements SendCachedEnvelopeFireAndForgetIntegration.SendFireAndForgetFactory {
    private final @NotNull SendCachedEnvelopeFireAndForgetIntegration.SendFireAndForgetDirPath
        sendFireAndForgetDirPath;

    /**
     * constructor
     *
     * @param sendFireAndForgetDirPath
     */
    public SendFireAndForgetOutboxSender(
        final @NotNull SendCachedEnvelopeFireAndForgetIntegration.SendFireAndForgetDirPath
            sendFireAndForgetDirPath) {
        this.sendFireAndForgetDirPath =
            Objects.requireNonNull(sendFireAndForgetDirPath, "SendFireAndForgetDirPath is required");
    }

    @Override
    public @Nullable SendCachedEnvelopeFireAndForgetIntegration.SendFireAndForget create(
        final @NotNull IHub hub, final @NotNull SentryOptions options) {
        Objects.requireNonNull(hub, "Hub is required");
        Objects.requireNonNull(options, "SentryOptions is required");

        final String dirPath = sendFireAndForgetDirPath.getDirPath();
        if (dirPath == null || !hasValidPath(dirPath, options.getLogger())) {
            options.getLogger().log(SentryLevel.ERROR, "No outbox dir path is defined in options.");
            return null;
        }

        final OutboxSender outboxSender =
            new OutboxSender(
                hub,
                options.getEnvelopeReader(),
                options.getSerializer(),
                options.getLogger(),
                options.getFlushTimeoutMillis());

        return processDir(outboxSender, dirPath, options.getLogger());
    }
}
